package vip.ola.pay.channel.yilianpiao.scanpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.channel.BasePayment;
import vip.ola.pay.channel.yilianpiao.cashierPay.CashierRequest;
import vip.ola.pay.channel.yilianpiao.cashierPay.OrderGoods;
import vip.ola.pay.channel.yilianpiao.cashierPay.OrderInfo;
import vip.ola.pay.channel.yilianpiao.cashierPay.TerminalInfo;
import vip.ola.pay.channel.yilianpiao.util.RsaUtils;

import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;

import static vip.ola.core.common.constant.PayEnum.ERR_0010;
import static vip.ola.core.common.constant.PayEnum.ERR_0121;

@Service
public class YlpscanPaymentService extends BasePayment {

    private static final MyLog _log = MyLog.getLog(YlpscanPaymentService.class);

    private static final String ENCODING = "utf-8";



    @Override
    public String getChannelName() {
        return "sfUnion";
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        try {
            _log.info("话费支付使用子账号ID：" + payOrder.getChannelMchId());
            PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String customerCode = payPassageAccount.getPassageMchId();
            String outTradeNo = payOrder.getPayOrderId();
            String reqUrl = accountParams.getString("payUrl");
            String notifyUrl = accountParams.getString("notify_url");
            String redirectUrl=accountParams.getString("callback_url");
            String terminalType=accountParams.getString("terminalType");
            String terminalId=accountParams.getString("terminalId");
            String privateKey=payPassageAccount.getPrivateKey();
            String signNo=accountParams.getString("sign_no");
            String version = "3.0";
            String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
            // 商户编号
            String clientIp = StringUtils.isNotEmpty(payOrder.getExtra())?payOrder.getExtra():payOrder.getClientIp(); // IP
            long payAmount = payOrder.getAmount(); // 支付金额,分为单位
            String payCurrency = "CNY"; // 币种，写死
            String attachData = "attachData"; // 备注数据,可空
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyyMMddHHmmss");
            String transactionStartTime = sdf.format(new Date()); // 交易开始时间
            String transactionEndTime = ""; // 交易结束时间
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId("10001");
            orderInfo.setBusinessType("100002");
            orderInfo.addGood(new OrderGoods("会员充值", String.valueOf(payAmount), 1));// 填写真实的订单信息如new
            // OrderGoods("订单信息",
            // "1箱", 1)
            CashierRequest order = new CashierRequest(version, outTradeNo, customerCode, clientIp, orderInfo, payAmount,
                    payCurrency, redirectUrl, attachData, transactionStartTime, transactionEndTime, nonceStr);
            order.setNotifyUrl(notifyUrl);
            // 终端信息
            TerminalInfo terminalInfo = new TerminalInfo();
            terminalInfo.setTerminal_type(terminalType);
            terminalInfo.setTerminal_id(terminalId);
            terminalInfo.setApp_version("1.0");
            terminalInfo.setTerminal_ip("127.0.0.1");
            // order.setTerminalInfo(terminalInfo);
            // 地区信息
            String areaInfo = getAreaInfoByIp(clientIp);
            order.setAreaInfo(areaInfo);

            // ----分账设置，如需分账，一定要传true
            order.setNeedSplit(false);
            // 是否限制信用卡支付，不填默认是false(即不限制)
            order.setNoCreditCards(false);
            String requestJson= JSONObject.toJSONString(order);
            String sign = RsaUtils.sign(privateKey, requestJson);
            Map<String , String> header = new HashMap<String , String>();
            header.put("x-efps-sign", sign);
            header.put("x-efps-sign-no", signNo);
            header.put("x-efps-sign-type","SHA256withRSA");
            header.put("x-efps-timestamp",sdf.format(new Date()));
            header.put("Content-Type", "application/json");
            _log.info("下单请求requestparam={}，hearder->{}",requestJson,header);
            String  response =doPostJson(reqUrl,header,requestJson);
            _log.info("下单返回={}",response);
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("更新订单状态为支付中: result={}", result);
            if (StringUtils.isNotEmpty(response)){
                JSONObject resObj = JSON.parseObject(response);
                if ("0000".equals(resObj.getString("returnCode")))
                {
                    String payUrl = resObj.getString("casherUrl");
                    return PayUtil.makeRetPayUrl(payUrl,null);
                }else {
                    String returnMsg = resObj.getString("returnMsg");
                    if (StringUtils.isNotEmpty(returnMsg)){
                        return  PayUtil.makeRetFail(returnMsg);
                    }
                }
            }else {
                return PayUtil.makeRetFail("上游通道异常");
            }

            return PayUtil.makeRetFail(ERR_0010);
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return PayUtil.makeRetFail(ERR_0010);
        }
    }

    private static String getAreaInfoByIp(String clientIp) {
        if (StringUtils.isEmpty(clientIp)){
            return "440106";
        }else {
            String queryUrl = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip="+clientIp;
            String resp = call(queryUrl,null);
            if (StringUtils.isNotEmpty(resp)){
                JSONObject resObj = JSON.parseObject(resp);
                String area =resObj.getString("cityCode");
                if (StringUtils.isNotEmpty(area) && "0".equals(area)){
                    return area;
                }else {
                    return "440106";
                }
            }else {
                return "440106";
            }
        }
    }

    public static String doPostJson(String url, Map<String, String> headerMap, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator(); // 循环增加header
                while (headerIterator.hasNext()) {
                    Map.Entry<String, String> elem = (Map.Entry<String, String>)headerIterator.next();
                    httpPost.addHeader(elem.getKey(), elem.getValue());
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        return null;
    }

    public static String queryDetail(String payOrderId, String queryUrl,String signNo, String mchId, String privateKey) {
        try {
            JSONObject query =new JSONObject();
            String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyyMMddHHmmss");
            query.put("customerCode",mchId);
            query.put("outTradeNo",payOrderId);
            query.put("nonceStr",nonceStr);
            String sign = RsaUtils.sign(privateKey, query.toJSONString());
            Map<String , String> header = new HashMap<String , String>();
            header.put("x-efps-sign", sign);
            header.put("x-efps-sign-no", signNo);
            header.put("x-efps-sign-type","SHA256withRSA");
            header.put("x-efps-timestamp",sdf.format(new Date()));
            header.put("Content-Type", "application/json");
            _log.info("查询请求requestparam={}，hearder->{}",query.toJSONString(),header);
            String  response =doPostJson(queryUrl,header,query.toJSONString());
            _log.info("查询返回={}",response);
            if (StringUtils.isNotEmpty(response)){
                JSONObject resObj = JSON.parseObject(response);
                if ("0000".equals(resObj.getString("returnCode")))
                {
                    return resObj.getString("payState");
                }else {
                    return null;
                }
            }else {
                return null;
            }
        }catch (Exception e){
            _log.error(e, "调用话费渠道异常。");
            return null;
        }

    }

    public static String getSign(Map<String,String> param, String signKey){
        SortedMap<String,String> map = new TreeMap<>(param);
        String str = "";
        map.remove("sign");
        for (Map.Entry<String,String> entry : map.entrySet()){
            if (entry.getValue() == null || "".equals(entry.getValue()) || "sign".equals(entry.getKey()))continue;
            str += entry.getValue();
        }
        return PayDigestUtil.md5(str+signKey,"UTF-8").toUpperCase();
    }

    public static String call(String url, Map<String,String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            _log.info("请求参数："+uri.toString());
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    @SneakyThrows
    public static void main(String[] args) {
        String customerCode = "562265003122220";
        String outTradeNo = "DD12023061223434673502";
//        String reqUrl = "http://test-efps.epaylinks.cn/api/txs/pay/UnifiedPayment";
//        String notifyUrl = "http://47.245.96.10:3503/api/ylpcash/notify";
//        String redirectUrl="http://47.245.96.10:3503/api/ylpcash/callback";
//        String terminalType="17";
//        String terminalId="70054167";
        String privateKey="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVaPSBsm6j+kRm4v+oy2b6hn3xt1czBcgUGhy00i97fccfOZI42FXr1dF+Y5EKefvcPSjiJZHezQyb/e6D9DIATF95r71cyLbmbxzb4PaDkVUuHYM1XeQSkTAD6kp3KAN8q6svxWYRkBajq0CZ359zT+Py8lKkfCXpj6mx6XlUrbmORPaRTu9m0V08Mg+hCOXiPXXLCxBpx+SjWHSvqgxqqo5R+Ks7Gjqtb0UJs0xE43w3Iuwpo4If/Bv4ScZ25RyhvL8v30x8kp2HI8z/BgXom6OrpMp/RBr27asXS/2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kbSQeleNvK5QP/Shsb8PUxBQeN/UQnq2zQQPXZAoGBALcEWSE0pjJTI36isHPz005GVe4TTyIzXDQ24I8JP7nMg+Z+zyjcAePmcg49vvmMD32rrSynb+CqeL8RUD3NkDU1KZ8HgKOOapub1YP6KqWfKX5nN1id70voVefNeKxnOcyk09KNT32TTguo6WQsDWxJI9MWHEeoHXLOT5K0FVpP";
        String signNo="562265003122220003";
//        String version = "3.0";
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
//        // 商户编号
//        String clientIp = "127.0.0.1"; // IP
//        long payAmount = 1000; // 支付金额,分为单位
//        String payCurrency = "CNY"; // 币种，写死
//        String attachData = "attachData"; // 备注数据,可空
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyyMMddHHmmss");
//        String transactionStartTime = sdf.format(new Date()); // 交易开始时间
//        String transactionEndTime = ""; // 交易结束时间
//        OrderInfo orderInfo = new OrderInfo();
//        orderInfo.setId("10001");
//        orderInfo.setBusinessType("100002");
//        orderInfo.addGood(new OrderGoods("会员充值", String.valueOf(payAmount), 1));// 填写真实的订单信息如new
//        // OrderGoods("订单信息",
//        // "1箱", 1)
//        CashierRequest order = new CashierRequest(version, outTradeNo, customerCode, clientIp, orderInfo, payAmount,
//                payCurrency, redirectUrl, attachData, transactionStartTime, transactionEndTime, nonceStr);
//        order.setNotifyUrl(notifyUrl);
//        // 终端信息
//        TerminalInfo terminalInfo = new TerminalInfo();
//        terminalInfo.setTerminal_type(terminalType);
//        terminalInfo.setTerminal_id(terminalId);
//        terminalInfo.setApp_version("1.0");
//        terminalInfo.setTerminal_ip("127.0.0.1");
//        // order.setTerminalInfo(terminalInfo);
//        // 地区信息
//        String areaInfo = getAreaInfoByIp(clientIp);
//        order.setAreaInfo(areaInfo);
//
//        // ----分账设置，如需分账，一定要传true
//        order.setNeedSplit(false);
//        // 是否限制信用卡支付，不填默认是false(即不限制)
//        order.setNoCreditCards(false);
//        String requestJson= JSONObject.toJSONString(order);
//        String sign = RsaUtils.sign(privateKey, requestJson);
//        Map<String , String> header = new HashMap<String , String>();
//        header.put("x-efps-sign", sign);
//        header.put("x-efps-sign-no", signNo);
//        header.put("x-efps-sign-type","SHA256withRSA");
//        header.put("x-efps-timestamp",sdf.format(new Date()));
//        header.put("Content-Type", "application/json");
//        _log.info("下单请求requestparam={}，hearder->{}",requestJson,header);
//        String  response =doPostJson(reqUrl,header,requestJson);
//        _log.info("下单返回={}",response);
        String queryUrl = "http://test-efps.epaylinks.cn/api/txs/pay/PaymentQuery";
        JSONObject query =new JSONObject();
        query.put("customerCode",customerCode);
        query.put("outTradeNo",outTradeNo);
        query.put("nonceStr",nonceStr);
        String sign = RsaUtils.sign(privateKey, query.toJSONString());
        Map<String , String> header = new HashMap<String , String>();
        header.put("x-efps-sign", sign);
        header.put("x-efps-sign-no", signNo);
        header.put("x-efps-sign-type","SHA256withRSA");
        header.put("x-efps-timestamp",sdf.format(new Date()));
        header.put("Content-Type", "application/json");
        _log.info("下单请求requestparam={}，hearder->{}",query.toJSONString(),header);
        String  response =doPostJson(queryUrl,header,query.toJSONString());
        _log.info("下单返回={}",response);
    }

}
